package cc.co.dreamind;

import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;
import android.R.drawable;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.*;

public class MoneyTallyActivity extends Activity {
	// invoke some variables:
	TextView tv_amount;
	// EditText et_reason;
	EditText et_reason_now;

	// amount control
	String[] st_temp = new String[50];
	// String st_last;
	boolean is_dot = false;
	int temp = 0;

	// edit reasons:
	static final int REASON_DIALOG_ID = 0;
	static final int OTHERREASON_DIALOG_ID = 3;
	int reason_id;
	View reason_view = null;
	boolean is_other_reason = false;
	String reason_temp;
	EditText et_reason_edit, et_amount_edit;
	Button[] bt_reason = new Button[10];
	Button bt_other_reason;
	Button bt_ensure_reason;

	// visibility
	public static final int VISIBLE = 0;
	public static final int INVISIBLE = 4;

	// date&time set
	Button bt_time;
	static final int DATE_DIALOG_ID = 1;
	static final int TIME_DIALOG_ID = 2;
	String st_time;
	boolean is_set_time = false;

	// db
	SQLiteDatabase db;
	public String db_name = "money.db";
	final dbHelper helper = new dbHelper(this, db_name, null, 1);
	// table_id
	static final int TB1_ID = 1;
	static final int TB2_ID = 2;
	static final int TB3_ID = 3;
	static final int TB_REASON_ID = 4;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		// get writable object from helper class
		// db = helper.getWritableDatabase();

		// keyboard Buttons:
		Button bt_num0 = (Button) findViewById(R.id.number0);
		bt_num0.setOnClickListener(new keyboard_listener());
		Button bt_num1 = (Button) findViewById(R.id.number1);
		bt_num1.setOnClickListener(new keyboard_listener());
		Button bt_num2 = (Button) findViewById(R.id.number2);
		bt_num2.setOnClickListener(new keyboard_listener());
		Button bt_num3 = (Button) findViewById(R.id.number3);
		bt_num3.setOnClickListener(new keyboard_listener());
		Button bt_num4 = (Button) findViewById(R.id.number4);
		bt_num4.setOnClickListener(new keyboard_listener());
		Button bt_num5 = (Button) findViewById(R.id.number5);
		bt_num5.setOnClickListener(new keyboard_listener());
		Button bt_num6 = (Button) findViewById(R.id.number6);
		bt_num6.setOnClickListener(new keyboard_listener());
		Button bt_num7 = (Button) findViewById(R.id.number7);
		bt_num7.setOnClickListener(new keyboard_listener());
		Button bt_num8 = (Button) findViewById(R.id.number8);
		bt_num8.setOnClickListener(new keyboard_listener());
		Button bt_num9 = (Button) findViewById(R.id.number9);
		bt_num9.setOnClickListener(new keyboard_listener());
		Button bt_dot = (Button) findViewById(R.id.dot);
		bt_dot.setOnClickListener(new keyboard_listener());
		// Button bt_plus = (Button)findViewById(R.id.plus);
		// bt_plus.setOnClickListener(new keyboard_listener());
		// Button bt_multiply = (Button)findViewById(R.id.multiply);
		// bt_multiply.setOnClickListener(new keyboard_listener());

		// reasons Buttons:
		Cursor c_reasons = helper.query("reasons");
		bt_reason[0] = (Button) findViewById(R.id.reason1);
		bt_reason[1] = (Button) findViewById(R.id.reason2);
		bt_reason[2] = (Button) findViewById(R.id.reason3);
		bt_reason[3] = (Button) findViewById(R.id.reason4);
		bt_reason[4] = (Button) findViewById(R.id.reason5);
		bt_reason[5] = (Button) findViewById(R.id.reason6);
		bt_reason[6] = (Button) findViewById(R.id.reason7);
		bt_reason[7] = (Button) findViewById(R.id.reason8);
		bt_reason[8] = (Button) findViewById(R.id.reason9);
		bt_reason[9] = (Button) findViewById(R.id.reason10);
		for (c_reasons.moveToFirst(); !c_reasons.isAfterLast(); c_reasons
				.moveToNext()) {
			int i = c_reasons.getInt(0);
			bt_reason[i].setText(c_reasons.getString(1));
		}
		for (int i = 0; i != 10; i++) {
			bt_reason[i].setOnClickListener(new reason_listener());
			bt_reason[i].setOnLongClickListener(new reason_edit_listener());
		}
		bt_other_reason = (Button) findViewById(R.id.other_reason_button);
		bt_other_reason.setOnClickListener(new other_reason_listener());
		et_reason_now = (EditText) findViewById(R.id.edit_reason);
		// et_reason_now.setOnClickListener(new bt_reason_now_listener());
		bt_ensure_reason = (Button) findViewById(R.id.ensure_reason);
		bt_ensure_reason.setOnClickListener(new ensure_reason_listener());
		// bt_clear_reason.setBackgroundResource(drawable.ic_delete);

		// time:
		// Button bt_time = (Button) findViewById(R.id.timenow);
		// bt_time.setOnClickListener(new time_button_listener());
		// tv_time = (TextView) findViewById(R.id.timenow);
		// Button bt_clear_time = (Button) findViewById(R.id.clear_time);
		// bt_clear_time.setOnClickListener(new delete_listener());
		// bt_clear_time.setBackgroundResource(drawable.ic_delete);

		// amount:
		Button bt_clear = (Button) findViewById(R.id.clear);
		bt_clear.setOnClickListener(new delete_listener());
		bt_clear.setOnLongClickListener(new clear_listener());
		bt_clear.setBackgroundResource(drawable.ic_input_delete);
		tv_amount = (TextView) findViewById(R.id.amount);
		// tv_amount.setMovementMethod(ScrollingMovementMethod.getInstance());

		// income & expend:
		Button bt_income = (Button) findViewById(R.id.income);
		bt_income.setOnClickListener(new in_out_listener());
		Button bt_expend = (Button) findViewById(R.id.expend);
		bt_expend.setOnClickListener(new in_out_listener());

		// list_button:
		Button bt_list = (Button) findViewById(R.id.list);
		bt_list.setOnClickListener(new list_listener());

		// Test Data output!

	}

	// Dialog
	@Override
	protected Dialog onCreateDialog(int id) {

		Calendar calendar = Calendar.getInstance();
		switch (id) {
		case OTHERREASON_DIALOG_ID:
			return new OtherReasonDialog(this);
		case DATE_DIALOG_ID:
			return new DatePickerDialog(this, date_listener,
					calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH),
					calendar.get(Calendar.DAY_OF_MONTH));
		case TIME_DIALOG_ID:
			return new TimePickerDialog(this, time_listener,
					calendar.get(Calendar.HOUR_OF_DAY),
					calendar.get(Calendar.MINUTE), true);
		case REASON_DIALOG_ID:
			return new ReasonEditDialog(this);
		}
		return super.onCreateDialog(id);
	}

	// reason_Dialog:
	public class ReasonEditDialog extends Dialog {

		public ReasonEditDialog(Context context) {
			super(context);
			this.setContentView(R.layout.dialog_reason);
			this.setTitle(R.string.title);
			et_reason_edit = (EditText) findViewById(R.id.reason_edit);
			et_amount_edit = (EditText) findViewById(R.id.amount_edit);
			Button bt_ensure = (Button) ReasonEditDialog.this
					.findViewById(R.id.reason_ensure);
			Button bt_cancel = (Button) ReasonEditDialog.this
					.findViewById(R.id.reason_cancel);
			bt_cancel.setOnClickListener(new View.OnClickListener() {

				public void onClick(View v) {
					et_reason_edit.requestFocus();
					et_reason_edit.setText("");
					et_amount_edit.setText("");
					ReasonEditDialog.this.dismiss();
				}

			});
			bt_ensure.setOnClickListener(new View.OnClickListener() {

				public void onClick(View v) {
					String st_reason = et_reason_edit.getText().toString();
					String st_amount = et_amount_edit.getText().toString();
					if (st_reason.length() == 0)
						Toast.makeText(getApplicationContext(),
								R.string.reason_empty, Toast.LENGTH_SHORT)
								.show();
					else {
						bt_reason[reason_id].setText(st_reason);
						tv_amount.setText(st_amount);
						helper.addreason(reason_id, st_reason, st_amount);
					}
					ReasonEditDialog.this.dismiss();
					et_reason_edit.requestFocus();
					et_reason_edit.setText("");
				}

			});
		}

	}

	// OtherReasonDialog:
	public class OtherReasonDialog extends Dialog {

		public OtherReasonDialog(Context context) {
			super(context);
			this.setContentView(R.layout.dialog_reason);
			this.setTitle(R.string.title);
			et_reason_edit = (EditText) findViewById(R.id.reason_edit);
			Timer timer = new Timer();
			timer.schedule(new TimerTask() {
				@Override
				public void run() {
					InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
					imm.showSoftInput(et_reason_edit,
							InputMethodManager.RESULT_SHOWN);
					imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,
							InputMethodManager.HIDE_IMPLICIT_ONLY);
				}

			}, 10);
			Button bt_ensure = (Button) OtherReasonDialog.this
					.findViewById(R.id.reason_ensure);
			Button bt_cancel = (Button) OtherReasonDialog.this
					.findViewById(R.id.reason_cancel);
			bt_ensure.setOnClickListener(new View.OnClickListener() {

				public void onClick(View v) {
					EditText et_reason = (EditText) findViewById(R.id.reason_edit);
					String st_reason = et_reason.getText().toString();
					if (st_reason.length() == 0)
						Toast.makeText(getApplicationContext(),
								R.string.reason_empty, Toast.LENGTH_SHORT)
								.show();
					else {
						et_reason_now.setText(st_reason);
					}
					InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
					imm.hideSoftInputFromWindow(
							et_reason_edit.getWindowToken(), 0);
					et_reason.requestFocus();
					et_reason.setText("");
					OtherReasonDialog.this.dismiss();
				}

			});
			bt_cancel.setOnClickListener(new View.OnClickListener() {

				public void onClick(View v) {
					et_reason_edit.requestFocus();
					et_reason_edit.setText("");
					InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
					imm.hideSoftInputFromWindow(
							et_reason_edit.getWindowToken(), 0);
					OtherReasonDialog.this.dismiss();
				}

			});
		}

	}

	// date_listener:
	DatePickerDialog.OnDateSetListener date_listener = new DatePickerDialog.OnDateSetListener() {

		public void onDateSet(DatePicker view, int year, int monthOfYear,
				int dayOfMonth) {

			st_time = "";
			/*
			 * Toast.makeText( getApplicationContext(), "date:" + year + "-" +
			 * (monthOfYear + 1) + "-" + dayOfMonth, Toast.LENGTH_SHORT).show();
			 */
			st_time = year + "." + (monthOfYear + 1) + "." + dayOfMonth;
			showDialog(TIME_DIALOG_ID);
		}
	};

	// time_listner:
	TimePickerDialog.OnTimeSetListener time_listener = new TimePickerDialog.OnTimeSetListener() {

		public void onTimeSet(TimePicker view, int hourOfDay, int minute) {

			/*
			 * Toast.makeText(getApplicationContext(), "time:" + hourOfDay + ":"
			 * + minute, Toast.LENGTH_SHORT) .show();
			 */
			st_time = st_time + " " + hourOfDay + ":" + minute;
			// Button bt_time = (Button) findViewById(R.id.timenow);
			bt_time.setText(st_time);
			is_set_time = true;
		}
	};

	// time_button_listener:
	class time_button_listener implements OnClickListener {

		public void onClick(View v) {
			showDialog(DATE_DIALOG_ID);
		}

	}

	// reason_long_click_edit_listener
	class reason_edit_listener implements OnLongClickListener {

		public boolean onLongClick(View v) {
			for (int i = 0; i != 10; i++) {
				if (v.getId() == bt_reason[i].getId())
					reason_id = i;
			}
			showDialog(REASON_DIALOG_ID);
			return false;
		}
	}

	// other_reason_listener:
	class other_reason_listener implements OnClickListener {

		public void onClick(View v) {
			// TODO Auto-generated method stub
			et_reason_now.setVisibility(VISIBLE);
			bt_ensure_reason.setVisibility(VISIBLE);
			Timer timer = new Timer();
			timer.schedule(new TimerTask() {
				@Override
				public void run() {
					InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
					imm.showSoftInput(et_reason_now,
							InputMethodManager.RESULT_SHOWN);
					imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,
							InputMethodManager.HIDE_IMPLICIT_ONLY);
				}

			}, 10);
		}

	}

	class ensure_reason_listener implements OnClickListener {

		public void onClick(View v) {
			// TODO Auto-generated method stub
			is_other_reason = true;
			if (reason_view != null)
				reason_view.setBackgroundColor(Color.BLACK);
			bt_other_reason.setBackgroundColor(Color.BLUE);
			bt_other_reason.setTextColor(Color.WHITE);
			InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
			imm.hideSoftInputFromWindow(et_reason_now.getWindowToken(), 0);
		}

	}

	// virtual keyboard listener:
	class keyboard_listener implements OnClickListener {

		public void onClick(View v) {
			if (temp < 9 && (is_dot == false || v.getId() != R.id.dot)) {
				Button bt = (Button) findViewById(v.getId());
				if (bt.getId() == R.id.dot)
					is_dot = true;
				st_temp[temp] = (String) tv_amount.getText();
				temp++;
				st_temp[temp] = (String) tv_amount.getText()
						+ (String) bt.getText();
				tv_amount.setText(st_temp[temp]);
			}
		}

	}

	// delete button listener:
	class delete_listener implements OnClickListener {

		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.clear:
				String s = st_temp[temp];
				if (temp != 0) {
					char ch_last = s.charAt(s.length() - 1);
					// Toast.makeText(getApplicationContext(),
					// String.valueOf(ch_last) , Toast.LENGTH_SHORT).show();
					tv_amount.setText(st_temp[temp - 1]);
					if (ch_last == '.')
						is_dot = false;
					temp--;
				}
				break;
			/*
			 * case R.id.clear_reason: bt_reason_now.setText(""); break; case
			 * R.id.clear_time: Button bt_time = (Button)
			 * findViewById(R.id.timenow);
			 * bt_time.setText(MoneyTallyActivity.this
			 * .getText(R.string.time_default)); st_time = ""; is_set_time =
			 * false; break;
			 */
			}

		}

	}

	// clear button listener:
	class clear_listener implements OnLongClickListener {

		public boolean onLongClick(View v) {
			tv_amount.setText("");
			temp = 0;
			is_dot = false;
			return false;
		}

	}

	// reason chosen button listener:
	class reason_listener implements OnClickListener {

		public void onClick(View v) {
			Button bt = (Button) findViewById(v.getId());
			et_reason_now.setText((String) bt.getText());

			// selected:
			if (is_other_reason == true)
				bt_other_reason.setBackgroundColor(Color.BLACK);
			if (reason_view != null)
				reason_view.setBackgroundColor(Color.BLACK);
			v.setBackgroundColor(Color.BLUE);
			reason_view = v;
		}
	}

	// income & expend Button Listener:
	class in_out_listener implements OnClickListener {

		public void onClick(View v) {
			if (tv_amount.getText().toString() != "") {
				Calendar calendar = Calendar.getInstance();
				String st_reason, st_amount;
				String st_sign = "";
				switch (v.getId()) {
				case R.id.income:
					st_sign = "";

					break;
				case R.id.expend:
					st_sign = "-";
					break;
				}
				st_amount = st_sign + tv_amount.getText();
				// sylar: st_amount to db.account1.amount;
				st_reason = et_reason_now.getText().toString();
				// sylar: st_reason to db.account1.reason;
				if (is_set_time == false)
					st_time = calendar.get(Calendar.YEAR) + "."
							+ calendar.get(Calendar.MONTH) + "."
							+ calendar.get(Calendar.DAY_OF_MONTH) + " "
							+ calendar.get(Calendar.HOUR_OF_DAY) + ":"
							+ calendar.get(Calendar.MINUTE);
				// sylar: st_time to db.account1.time;
				helper.addterm(st_reason, st_amount, st_time, 1);

				// test code:
				Toast.makeText(getApplicationContext(),
						st_time + " " + st_reason + " " + st_amount,
						Toast.LENGTH_SHORT).show();

				// end of income&expend
				is_set_time = false;
				tv_amount.setText("");
				et_reason_now.setText("");
				// Button bt_time = (Button) findViewById(R.id.timenow);
				// bt_time.setText(MoneyTallyActivity.this.getText(R.string.time_default));
				temp = 0;
				is_dot = false;

			} else
				Toast.makeText(getApplicationContext(), R.string.amount_empty,
						Toast.LENGTH_SHORT).show();
		}

	}

	class list_listener implements OnClickListener {

		public void onClick(View arg0) {
			Intent intent = new Intent(MoneyTallyActivity.this, list.class);
			MoneyTallyActivity.this.startActivity(intent);
		}

	}

	public class bt_reason_now_listener implements OnClickListener {

		public void onClick(View v) {
			showDialog(OTHERREASON_DIALOG_ID);
		}

	}

}
